package com.ruoyi.business.controller;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.business.domain.Station;
import com.ruoyi.business.domain.dto.CityWithPlatformsDTO;
import com.ruoyi.business.domain.vo.PlatformVo;
import com.ruoyi.business.service.IStationService;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Platform;
import com.ruoyi.business.service.IPlatformService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 车站管理Controller
 *
 * @author ruoyi
 * @date 2025-03-21
 */
@RestController
@RequestMapping("/base/platform")
public class PlatformController extends BaseController {
    @Autowired
    private IPlatformService platformService;

    @Autowired
    private IStationService stationService;

    /**
     * 查询车站管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:platform:list')")
    @GetMapping("/list")
    public TableDataInfo list(Platform platform) {
        startPage();
        List<Platform> list = platformService.selectPlatformList(platform);
        return getDataTable(list);
    }

    /**
     * 查询车站管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:platform:list')")
    @GetMapping("/StationNameList")
    public List selectPlatformStationName() {
        return platformService.selectPlatformList(new Platform());
    }

    /**
     * 导出车站管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:platform:export')")
    @Log(title = "车站管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Platform platform) {
        List<Platform> list = platformService.selectPlatformList(platform);
        ExcelUtil<Platform> util = new ExcelUtil<Platform>(Platform.class);
        util.exportExcel(response, list, "车站管理数据");
    }

    /**
     * 导入每日车次列表
     */
//    @PreAuthorize("@ss.hasPermi('base:platform:add')")
//    @Log(title = "车站管理", businessType = BusinessType.IMPORT)
//    @PostMapping("/importExcel")
//    public AjaxResult importExcel(MultipartFile file) throws IOException {
//        ExcelUtil<PlatformVo> util = new ExcelUtil<PlatformVo>(PlatformVo.class);
//        List<PlatformVo> list = util.importExcel(file.getInputStream());
//        List<Platform> platformList = new ArrayList<>();
//        for (PlatformVo platformVo : list) {
//            Platform platform = new Platform();
//            platform.setId(IdUtil.getSnowflakeNextId());
//            platform.setCityId(platformVo.getCityId());
//            platform.setStationName(platformVo.getStationName());
//            platform.setStationPinyin(platformVo.getStationPinyin());
//            platform.setStationInitials(platformVo.getStationInitials());
//            platform.setStationType(platformVo.getStationType());
//            platformList.add(platform);
//        }
//        return toAjax(platformService.insertPlatforms(platformList));
//    }
    /**
     * 导入车站列表
     */
    @PreAuthorize("@ss.hasPermi('base:platform:add')")
    @Log(title = "车站管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file) throws IOException {
        logger.info("开始导入Excel文件: {}", file.getOriginalFilename());
        
        try {
            ExcelUtil<PlatformVo> util = new ExcelUtil<PlatformVo>(PlatformVo.class);
            List<PlatformVo> list = util.importExcel(file.getInputStream());
            
            logger.info("成功解析Excel文件，获取到{}条数据", list.size());
            
            // 校验唯一性，分离有效数据和无效数据
            List<Map<String, Object>> errorList = new ArrayList<>();
            List<Platform> validPlatforms = new ArrayList<>();

            for (int i = 0; i < list.size(); i++) {
                PlatformVo platformVo = list.get(i);
                logger.debug("处理第{}行数据: id={}, cityId={}, stationName={}", 
                    i + 1, platformVo.getId(), platformVo.getCityId(), platformVo.getStationName());
                
                boolean isDuplicate = false;

                // 获取原始ID，保持原样不做修改
                Long id = platformVo.getId();
                
                // 检查必填字段
                if (platformVo.getCityId() == null || StringUtils.isEmpty(platformVo.getStationName())) {
                    Map<String, Object> error = new HashMap<>();
                    error.put("id", id);
                    error.put("rowNum", i + 2);
                    error.put("cityId", platformVo.getCityId());
                    error.put("stationName", platformVo.getStationName());
                    error.put("stationPinyin", platformVo.getStationPinyin());
                    error.put("stationInitials", platformVo.getStationInitials());
                    error.put("stationType", platformVo.getStationType());
                    error.put("errorMsg", "城市ID和站点名称不能为空");
                    errorList.add(error);
                    logger.warn("第{}行数据验证失败: 必填字段为空", i + 1);
                    continue;
                }

                // 检查此组合是否已存在（城市ID + 站点名称）
                boolean exists = platformService.existsPlatformByCityIdAndStationName(
                        platformVo.getCityId(), platformVo.getStationName());

                if (exists) {
                    Map<String, Object> error = new HashMap<>();
                    error.put("id", id);
                    error.put("rowNum", i + 2);
                    error.put("cityId", platformVo.getCityId());
                    error.put("stationName", platformVo.getStationName());
                    error.put("stationPinyin", platformVo.getStationPinyin());
                    error.put("stationInitials", platformVo.getStationInitials());
                    error.put("stationType", platformVo.getStationType());
                    error.put("errorMsg", "车站已存在");
                    errorList.add(error);
                    isDuplicate = true;
                    logger.warn("第{}行数据验证失败: 车站已存在", i + 1);
                }

                // 如果不是重复数据，添加到有效数据列表
                if (!isDuplicate) {
                    Platform platform = new Platform();
                    platform.setId(id);
                    platform.setCityId(platformVo.getCityId());
                    platform.setStationName(platformVo.getStationName());
                    platform.setStationPinyin(platformVo.getStationPinyin());
                    platform.setStationInitials(platformVo.getStationInitials());
                    platform.setStationType(platformVo.getStationType());
                    validPlatforms.add(platform);
                    logger.debug("第{}行数据验证通过", i + 1);
                }
            }

            // 插入有效数据
            int successCount = 0;
            if (!validPlatforms.isEmpty()) {
                successCount = platformService.insertPlatforms(validPlatforms);
                logger.info("成功导入{}条数据", successCount);
            }

            // 构建响应
            if (!errorList.isEmpty()) {
                logger.warn("导入完成，有{}条错误数据", errorList.size());
                AjaxResult ajaxResult = AjaxResult.error("部分数据导入成功，部分数据导入失败", errorList);
                ajaxResult.put("successCount", successCount);
                return ajaxResult;
            } else {
                logger.info("导入完成，全部{}条数据导入成功", successCount);
                return AjaxResult.success("成功导入" + successCount + "条数据");
            }
        } catch (Exception e) {
            logger.error("导入Excel失败", e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
    /**
     * 下载车站导入模板
     */
    @PreAuthorize("@ss.hasPermi('base:platform:export')")
    @Log(title = "车站管理", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<PlatformVo> util = new ExcelUtil<>(PlatformVo.class);
        util.importTemplateExcel(response, "车站管理数据");
    }


    /**
     * 获取车站管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:platform:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(platformService.selectPlatformById(id));
    }

    /**
     * 新增车站管理
     */
    @PreAuthorize("@ss.hasPermi('base:platform:add')")
    @Log(title = "车站管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Platform platform) {
        return toAjax(platformService.insertPlatform(platform));
    }

    /**
     * 修改车站管理
     */
    @PreAuthorize("@ss.hasPermi('base:platform:edit')")
    @Log(title = "车站管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Platform platform) {
        return toAjax(platformService.updatePlatform(platform));
    }

    /**
     * 删除车站管理
     */
    @PreAuthorize("@ss.hasPermi('base:platform:remove')")
    @Log(title = "车站管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(platformService.deletePlatformByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('base:platform:list')")
    @GetMapping("/listByCity")
    public TableDataInfo listByCity(Platform platform) {
        System.out.println(platform.toString() + "papapapappapapap");

        // 获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取分页参数
        int pageNum = getParameterToInt(request, "pageNum", 1);
        int pageSize = getParameterToInt(request, "pageSize", 10);
        System.out.println("PageNum: " + pageNum + ", PageSize: " + pageSize);

        // 1. 查询所有车站
        List<Station> cities = stationService.selectStationList(new Station());
        System.out.println("Cities size: " + cities.size());
        for (Station city : cities) {
            System.out.println(city + "!#@!#@!!@$!@#!#@!@#");
        }

        // 2. 查询每个车站下的车站并组装数据
        List<CityWithPlatformsDTO> result = new ArrayList<>();

        for (Station city : cities) {
            System.out.println("City ID: " + city.getId() + "ididiidididdii");
            // 创建DTO对象
            CityWithPlatformsDTO cityDto = new CityWithPlatformsDTO();
            cityDto.setId(city.getId());
            cityDto.setName(city.getName());

            // 查询该车站下的车站
            Platform query = new Platform();
            query.setCityId(city.getId());
            if (StringUtils.isNotBlank(platform.getStationName())) {
                query.setStationName(platform.getStationName());
            }
            if (StringUtils.isNotBlank(platform.getSname())) {
                query.setSname(platform.getSname());
            }
            System.out.println("Query: " + query + "qwwqqwqwqwqwqw");
            List<Platform> platforms = platformService.selectCitiesWithPlatforms(query);
            System.out.println("Platforms size: " + platforms.size());

            // 设置车站列表
            cityDto.setPlatforms(platforms);

            // 添加到结果中
            if (platforms != null && platforms.size() > 0) {
                result.add(cityDto);
            }
        }

        // 3. 获取前 pageSize 条数据
        int offset = (pageNum - 1) * pageSize;
        List<CityWithPlatformsDTO> paginatedResult = new ArrayList<>();
        if (offset < result.size()) {
            int end = Math.min(offset + pageSize, result.size());
            paginatedResult = result.subList(offset, end);
        }

        // 4. 返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(paginatedResult);
        rspData.setTotal(result.size());

        return rspData;
    }

    /**
     * 自定义方法：从请求中获取整数参数
     */
    private int getParameterToInt(HttpServletRequest request, String name, int defaultValue) {
        String value = request.getParameter(name);
        if (value != null) {
            try {
                return Integer.parseInt(value);
            } catch (NumberFormatException e) {
                // 如果转换失败，返回默认值
                return defaultValue;
            }
        }
        return defaultValue;
    }

    /**
     * 导出错误数据
     */
    @PreAuthorize("@ss.hasPermi('base:platform:export')")
    @Log(title = "车站管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportErrorData")
    public void exportErrorData(HttpServletResponse response, @RequestParam(required = false) String errorData) throws IOException {
        if (StringUtils.hasText(errorData)) {
            try {
                logger.info("收到的错误数据: {}", errorData);
                
                ObjectMapper mapper = new ObjectMapper();
                List<Map<String, Object>> dataList = mapper.readValue(errorData, 
                    mapper.getTypeFactory().constructCollectionType(List.class, Map.class));
                
                logger.info("解析后的错误数据: {}", dataList);
                
                List<PlatformVo> voList = new ArrayList<>();
                
                for (Map<String, Object> item : dataList) {
                    PlatformVo vo = new PlatformVo();
                    logger.info("处理错误项: {}", item);
                    
                    // 处理ID字段
                    if (item.get("id") != null) {
                        try {
                            vo.setId(Long.parseLong(item.get("id").toString()));
                            logger.info("成功解析ID: {}", vo.getId());
                        } catch (Exception e) {
                            logger.error("解析ID失败: {}", e.getMessage());
                        }
                    }
                    
                    // 处理城市ID字段
                    if (item.get("cityId") != null) {
                        try {
                            vo.setCityId(Long.parseLong(item.get("cityId").toString()));
                            logger.info("成功解析城市ID: {}", vo.getCityId());
                        } catch (Exception e) {
                            logger.error("解析城市ID失败: {}", e.getMessage());
                        }
                    }
                    
                    // 其他字符串字段的处理
                    vo.setStationName(item.get("stationName") != null ? item.get("stationName").toString() : null);
                    vo.setStationPinyin(item.get("stationPinyin") != null ? item.get("stationPinyin").toString() : null);
                    vo.setStationInitials(item.get("stationInitials") != null ? item.get("stationInitials").toString() : null);
                    
                    // 处理车站类型字段
                    vo.setStationType(item.get("stationType") != null ? item.get("stationType").toString() : "1");
                    logger.info("设置车站类型: {}", vo.getStationType());
                    
                    // 设置错误信息
                    vo.setErrorMsg(item.get("errorMsg") != null ? item.get("errorMsg").toString() : null);
                    
                    // 处理行号字段
                    if (item.get("rowNum") != null) {
                        try {
                            vo.setRowNum(Integer.parseInt(item.get("rowNum").toString()));
                        } catch (Exception e) {
                            logger.error("解析行号失败: {}", e.getMessage());
                        }
                    }
                    
                    voList.add(vo);
                    logger.info("添加到导出列表: {}", vo);
                }
                
                logger.info("转换后的错误数据对象数量: {}", voList.size());
                for (PlatformVo vo : voList) {
                    logger.info("导出错误数据: id={}, cityId={}, stationName={}, stationType={}, errorMsg={}", 
                        vo.getId(), vo.getCityId(), vo.getStationName(), vo.getStationType(), vo.getErrorMsg());
                }
                
                platformService.exportCustomErrorData(response, voList);
                
            } catch (Exception e) {
                logger.error("处理错误数据失败", e);
                platformService.exportCustomErrorData(response, new ArrayList<>());
            }
        } else {
            logger.warn("没有错误数据，导出空表");
            platformService.exportCustomErrorData(response, new ArrayList<>());
        }
    }

    /**
     * 清空车站数据
     */
    @PreAuthorize("@ss.hasPermi('base:platform:remove')")
    @Log(title = "车站管理", businessType = BusinessType.CLEAN)
    @PostMapping("/clear")
    public AjaxResult clear(@RequestBody Map<String, String> passwordMap) {
        String password = passwordMap.get("password");
        System.out.println("密码：" + password);
        // 验证当前用户密码
        if (!SecurityUtils.matchesPassword(password, SecurityUtils.getLoginUser().getPassword())) {
            return AjaxResult.error("密码验证失败");
        }
        return toAjax(platformService.clearPlatform());
    }
}
